package com.uetoken.cn.activity;

import android.content.Intent;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.BarUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.RegexUtils;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.uetoken.cn.R;
import com.uetoken.cn.base.BaseActivity;
import com.uetoken.cn.bean.ModifyPhoneSuccessEvent;
import com.uetoken.cn.common.ApiHelper;
import com.uetoken.cn.common.Constant;
import com.uetoken.cn.network.OkHttpUtils;
import com.uetoken.cn.network.Params;
import com.uetoken.cn.network.WebResponse;
import com.uetoken.cn.utils.CountDownTimerUtils;

import org.greenrobot.eventbus.EventBus;

import java.io.IOException;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

/**
 * 输入新的手机号界面
 */
public class InputNewPhoneActivity extends BaseActivity implements WebResponse {

    @BindView(R.id.iv_back)
    ImageView mIvBack;
    @BindView(R.id.tv_title)
    TextView mTvTitle;
    @BindView(R.id.edt_activity_input_new_phone)
    EditText mEdtActivityInputNewPhone;
    @BindView(R.id.tv_activity_input_new_phone_get_verification_code)
    TextView mTvGetVerificationCode;
    @BindView(R.id.edt_activity_input_new_phone_please_input_verification_code)
    EditText mEdtInputVerificationCode;
    @BindView(R.id.tv_activity_input_new_phone_confirm_modify)
    TextView mTveConfirmModify;
    private CountDownTimerUtils countDownTimerUtils;
    /**
     * 获取验证码网络请求码
     */
    private static final int NETWORK_REQUEST_GET_CODE = 10;
    /**
     * 修改手机号
     */
    private static final int NETWORK_REQUEST_MODIFY_PHONE = 20;
    /**
     * 旧手机号
     */
    private String oldPhone;
    /**
     * 旧手机号验证码
     */
    private String oldCode;

    @Override
    public int getLayoutId() {
        return R.layout.activity_input_new_phone;
    }

    @Override
    public void initView() {
        ButterKnife.bind(this);

        //状态栏沉浸式
        BarUtils.setStatusBarColor(this, ContextCompat.getColor(this, android.R.color.white), true);
        BarUtils.setStatusBarLightMode(this, true);

        mTvTitle.setText(getResources().getString(R.string.str_input_new_phone));
        mIvBack.setVisibility(View.VISIBLE);

    }

    @Override
    public void initData() {
        Intent intent = getIntent();
        oldPhone = intent.getStringExtra("phone");
        oldCode = intent.getStringExtra("code");
    }

    @Override
    public void init() {

    }

    @OnClick({R.id.iv_back, R.id.tv_activity_input_new_phone_get_verification_code, R.id.tv_activity_input_new_phone_confirm_modify})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.tv_activity_input_new_phone_get_verification_code:
                getVerificationCode();
                break;
            case R.id.tv_activity_input_new_phone_confirm_modify:
                modifyPhone();
                break;
        }
    }

    /**
     * 修改手机号
     */
    private void modifyPhone() {
        String newPhone = mEdtActivityInputNewPhone.getText().toString().trim();
        String newCode = mEdtInputVerificationCode.getText().toString().trim();
        if (TextUtils.isEmpty(newPhone)) {
            ToastUtils.showShort(getResources().getString(R.string.str_phone_not_be_empty));
            return;
        }
        if (!RegexUtils.isMobileSimple(newPhone)) {
            ToastUtils.showShort(getResources().getString(R.string.str_phone_not_specification));
            return;
        }
        if (TextUtils.isEmpty(newCode)) {
            ToastUtils.showShort(getResources().getString(R.string.str_auth_code_not_empty));
            return;
        }
        showLoading();
        OkHttpUtils.getInstance().getStringWithParam(this, ApiHelper.getModifyUserPhoneUrl(), NETWORK_REQUEST_MODIFY_PHONE, Params.getModifyUserPhoneParams(
                oldPhone, newPhone, oldCode, newCode));
    }

    /**
     * 获取验证码
     */
    private void getVerificationCode() {
        String phone = mEdtActivityInputNewPhone.getText().toString().trim();

        if (TextUtils.isEmpty(phone)) {
            ToastUtils.showShort(getResources().getString(R.string.str_phone_not_be_empty));
            return;
        }
        if (!RegexUtils.isMobileSimple(phone)) {
            ToastUtils.showShort(getResources().getString(R.string.str_phone_not_specification));
            return;
        }
        countDownTimerUtils = new CountDownTimerUtils(this, mTvGetVerificationCode, 60000, 1000);
        countDownTimerUtils.start();
        //调用接口获取验证码
        OkHttpUtils.getInstance().getStringWithParam(InputNewPhoneActivity.this, ApiHelper.getSendSMSUrl(), NETWORK_REQUEST_GET_CODE, Params.getSmsParams(phone));
    }

    @Override
    public void onSuccessResponse(Call call, String response, int requestCode) throws IOException {
        switch (requestCode) {
            case NETWORK_REQUEST_GET_CODE:
                break;
            case NETWORK_REQUEST_MODIFY_PHONE:
                dissmissDialog();
                try {
                    JsonObject obj = new JsonParser().parse(response).getAsJsonObject();
                    int result = obj.get("result").getAsInt();
                    String message = obj.get("message").getAsString();
                    if (result > 0) {
                        ToastUtils.showShort(message);
                        String newPhone = mEdtActivityInputNewPhone.getText().toString().trim();
                        //修改手机号成功后更新保存在本地的手机号
                        SPUtils.getInstance(Constant.UE_TOKEN_PREFERENCE_USER_INFO).put(Constant.SP_MOBILE_NO, newPhone);
                        //更新用户信息界面的手机号
                        EventBus.getDefault().post(new ModifyPhoneSuccessEvent(newPhone));

                        //通知主activity刷新界面
                        Intent successIntent = new Intent();
                        successIntent.setAction("paySuccess");
                        sendBroadcast(successIntent);

                        ActivityUtils.finishActivity(ModifyUserInfoActivity.class);
                        finish();
                    } else {
                        ToastUtils.showShort(message);
                    }
                } catch (Exception e) {
                    LogUtils.e(e.toString());
                }
                break;
        }
    }

    @Override
    public void onFailResponse(Call call, IOException e, int requestCode) {
        dissmissDialog();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (countDownTimerUtils != null) {
            countDownTimerUtils.cancel();
        }
    }
}
